﻿using Nature.Core.Config;
using Shuttle.Core.Data;
using Shuttle.ESB.Core;
using Shuttle.ESB.SqlServer;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace Nature.Core.Distributed
{
    public class ServiceBusManager
    {
        //服务总线
        static private IServiceBus _bus;
        //已发布的事件
        static IList<string> _publishedEvents = new List<string>();
        //获取已订阅的事件
        public static string[] GetSubscribedEvents()
        {
            return _publishedEvents.ToArray();
        }
        //订阅事件
        public static void Subscribe(Type eventType)
        {
            if (!_publishedEvents.Contains(eventType.FullName))
            {
                _publishedEvents.Add(eventType.FullName);
            }
        }
        //发布事件
        public static void Publish(object theEvent)
        {
            _bus.Publish(theEvent);
        }
        //开始服务总线
        public static void Start()
        {
            //启动服务本身
            new ConnectionStringService().Approve();
            var subscriptionManager = SubscriptionManager.Default();
            subscriptionManager.Subscribe(
                ServiceBusManager.GetSubscribedEvents()
            );
            _bus = ServiceBus.Create(c => 
                c.SubscriptionManager(subscriptionManager)
                ).Start();
        }
        //释放服务总线
        public static void Dispose()
        {
            _bus.Dispose();
        }
    }
}
